package batch

import (
	"fmt"
	
	"mariadb-operator/pkg/apis/finupgroup/v1alpha1"

	batchv1 "k8s.io/api/batch/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// NewJob will return a new kubernetes job
func NewJob(backup *v1alpha1.MariaDBBackup) *batchv1.Job {
	image, backupCMD := help(backup.Spec)
	envs := envs(backup.Spec, backup.Spec.Cluster, backup.Namespace)
	job := &batchv1.Job{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "batch/v1",
			Kind:       "Job",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name:      backup.Name,
			Namespace: backup.Namespace,
		},
		Spec: batchv1.JobSpec{
			Template: corev1.PodTemplateSpec{
				Spec: corev1.PodSpec{
					RestartPolicy: corev1.RestartPolicyOnFailure,
					Volumes: []corev1.Volume{
						corev1.Volume{
							Name: "backup",
							VolumeSource: corev1.VolumeSource{
								EmptyDir: &corev1.EmptyDirVolumeSource{},
							},
						},
					},
					InitContainers: []corev1.Container{
						corev1.Container{
							ImagePullPolicy: corev1.PullAlways,
							Name:            fmt.Sprintf("init-%v", backup.Name),
							Image:           image,
							Command:         []string{"bash", "-c", backupCMD},
							VolumeMounts: []corev1.VolumeMount{
								corev1.VolumeMount{
									Name:      "backup",
									MountPath: "/tmp",
								},
							},
							Env: envs,
						},
					},
					Containers: []corev1.Container{
						corev1.Container{
							ImagePullPolicy: corev1.PullAlways,
							Name:            backup.Name,
							Image:           image,
							Command:         []string{"bash", "-c", "mariadb-backup"},
							VolumeMounts: []corev1.VolumeMount{
								corev1.VolumeMount{
									Name:      "backup",
									MountPath: "/tmp",
								},
							},
							Env: envs,
						},
					},
				},
			},
		},
	}
	return job
}
